﻿using Castle.Core;
using Castle.Core.Configuration;
using Castle.Core.Logging;
using Castle.MicroKernel.Facilities;
using org.apache.solr.SolrSharp.Configuration;
using org.apache.solr.SolrSharp.Update;
using SolrSharp.Adapters;

namespace Castle.Facilities.SolrSharp {
	public class SolrSharpFacility : AbstractFacility {
		private ILogger log = NullLogger.Instance;

		public ILogger Log {
			get { return log; }
			set { log = value; }
		}

		protected override void Init() {
			if (FacilityConfig == null) {
				log.Fatal("Configuration for SolrSharp Facility not found");
				throw new FacilityException("Configuration for SolrSharp Facility not found");
			}
			var searcherConfig = new MutableConfiguration("SolrSearcher");
			var searcherParameters = searcherConfig.Children.Add(new MutableConfiguration("parameters"));
			searcherParameters.Children.Add(new MutableConfiguration("solrUrl", FacilityConfig.Children["solrUrl"].Value)); // "http://localhost:8983/solr/"));
			string searcherMode = "ReadWrite";
			if (FacilityConfig.Children["searcherMode"] == null)
				searcherParameters.Children.Add(new MutableConfiguration("searcherMode", FacilityConfig.Children["searcherMode"].Value)); // "ReadWrite"));
			Kernel.ConfigurationStore.AddComponentConfiguration("SolrSearcher", searcherConfig);
			Kernel.AddComponent("SolrSearcher", typeof (SolrSearcher));
			Kernel.AddComponent("SolrSearcherAdapter", typeof (ISolrSearcher), typeof (SolrSearcherAdapter));
			Kernel.AddComponent("SolrUpdater", typeof (SolrUpdater));
			Kernel.AddComponent("SolrUpdaterAdapter", typeof (ISolrUpdater), typeof (SolrUpdaterAdapter));
			Kernel.AddComponent("SolrQueryBuilder", typeof (ISolrQueryBuilder), typeof (SolrQueryBuilder), LifestyleType.Transient);
		}
	}
}